package com.hxzy.controller;

import com.hxzy.common.constans.Update;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.R;
import com.hxzy.dto.MerchandiserSearchDTO;
import com.hxzy.entity.Employee;
import com.hxzy.entity.MerchandiseClass;
import com.hxzy.entity.Merchandiser;
import com.hxzy.service.MerchandiserService;
import com.hxzy.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商家API
 * @author Administrator
 */
@Api(tags = "商家API")
@RestController
@RequestMapping(value = "/api/merchandiser")
public class MerchandiserController extends BaseController {

    @Autowired
    private MerchandiserService merchandiserService;

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R search(MerchandiserSearchDTO searchDTO){
        //如果是商家就只允许查询自己的
        if(!WaimaiThreadLocal.isSuperMan()){
            searchDTO.setMerchantId(WaimaiThreadLocal.getCurrent().getAccountVO().getId());
        }

        super.startPageHelper();
        List<Merchandiser> arrList=this.merchandiserService.search(searchDTO);
        return super.pageToPageVO(arrList);
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R findById(@PathVariable(value = "id") Long id){
        LoginVO current = WaimaiThreadLocal.getCurrent();

        if(!WaimaiThreadLocal.isSuperMan()){
            if(!id.equals(current.getAccountVO().getId())){
                return R.build(AckCode.VALUE_NOT_CHANGE);
            }
        }

        Merchandiser merchandiser =  this.merchandiserService.selectByPrimaryKey(id);
        if(merchandiser==null){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        return R.okHasData(merchandiser);
    }

    @ApiOperation(value = "修改")
    @PutMapping
    public R update(@RequestBody @Validated(value = {Update.class}) Merchandiser merchandiser){

        //验证账户被修改过没有
        Merchandiser db = this.merchandiserService.selectByPrimaryKey(merchandiser.getId());
        if(db==null){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        if(!merchandiser.getLoginName().equals(db.getLoginName())){
            return R.build(AckCode.ACCOUNT_NAME_NOT_MODIFY);
        }

        //自己赋值
        merchandiser.setStatus(db.getStatus());
        boolean result = this.merchandiserService.updateById(merchandiser);
        return super.toR(result);
    }
}
